#pragma once
#include <brpc/server.h>
#include <butil/logging.h>
#include <functional>
#include "etcd.hpp"
#include "logger.hpp"
#include "user.pb.h"
#include "base.pb.h"
#include "file.pb.h"
#include "data_es.hpp"
#include "mysql_user.hpp"
#include "data_redis.hpp"
#include "channel.hpp"
#include "dms.hpp"
#include "utils.hpp"
#include "user.hxx"

namespace zhiang
{

class UserServiceImpl : public zhiang::UserService {
private:
    bool check_nickname(const std::string& nickname) {
        int sz = nickname.size();
        if(sz < 1 || sz > 25) return false;
        // for(const char c : nickname) {
        //     if((c >= '0' || c <= '9') || (c >= 'a' || c <= 'z') || (c >= 'A' || c <= 'Z') || c == '-' || c == '-') {}
        //     else return false;
        // }
        return true;
    } 
    bool check_password(const std::string& password) {
        int sz = password.size();
        if(sz < 6 || sz > 25) return false;
        for(const char c : password) {
            if((c >= '0' || c <= '9') || (c >= 'a' || c <= 'z') || (c >= 'A' || c <= 'Z') || c == '-' || c == '-' || c == '.') {}
            else return false;
        }
        return true;
    } 
    bool check_phone(const std::string& phone) {
        if(phone.size() != 11) {
            LOG_DEBUG("{} - phone.size != 11", phone);
            return false;
        }
        if(phone[0] != '1') {
            LOG_DEBUG("{} - phone[0] != 1", phone);
            return false;
        }
        for(const char& c : phone) 
            if(c > '9' || c < '0') {
                LOG_DEBUG("{} - c > '9' || c < '0'", c);
                return false;
            }
        return true;
    }
public:
    UserServiceImpl(const DMSClient::ptr& dms_client,
        const std::shared_ptr<elasticlient::Client>& es_client,
        const std::shared_ptr<odb::core::database>& mysql_client,
        const std::shared_ptr<sw::redis::Redis>& redis_client,
        const std::string& discovery_file_name,
        const ServiceManage::ptr& serviceManage_channal) :
        _es_user(std::make_shared<ESUser>(es_client)),
        _mysql_user(std::make_shared<UserTable>(mysql_client)),
        _redis_session(std::make_shared<Session>(redis_client)),
        _redis_status(std::make_shared<Status>(redis_client)),
        _redis_codes(std::make_shared<Codes>(redis_client)),
        _discovery_file_name(discovery_file_name),
        _serviceManage_channal(serviceManage_channal),
        _dms_client(dms_client){
        _es_user->createIndex();
    }
    ~UserServiceImpl(){}

    void UserRegister(::google::protobuf::RpcController* controller,
                         const ::zhiang::UserRegisterReq* request,
                         ::zhiang::UserRegisterRsp*response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        // 1.从请求中取出昵称和密码 
        std::string nickname = request->nickname();
        std::string password = request->password();
        // 2.检查昵称是否合法（只能包含字母，数字，连字符-，下划线_，长度限制3~15之间） 
        bool ret = check_nickname(nickname);
        if(!ret) {
            LOG_ERROR("{} - {} 用户昵称不合法", request->request_id(), nickname);
            return errorResp("用户昵称不合法");
        }
        // 3.检查密码是否合法（只能包含字母，数字，长度限制6~15之间） 
        ret = check_password(password);
        if(!ret) {
            LOG_ERROR("{} - {} 用户密码不合法", request->request_id(), password);
            return errorResp("用户密码不合法");
        }
        // 4.根据昵称在数据库进行判断是否昵称已存在 
        std::shared_ptr<User> user = _mysql_user->select_by_nickname(nickname);
        if(user) {
            LOG_INFO("{} 该昵称已存在", nickname);
            return errorResp("该昵称已存在");
        }
        // 5.向数据库新增数据 
        std::string uid = generate_uid();
        user = std::make_shared<User>(uid, nickname, password);
        ret = _mysql_user->insert(user);
        if(!ret) {
            LOG_ERROR("{} - MySQL插入User数据失败", request->request_id());
            return errorResp("MySQL插入User数据失败");
        }
        // 6.向ES服务器中新增用户信息 
        ret = _es_user->appendData(user->user_id(), user->nickname(), user->description(), user->phone(), user->avatar_id());
        if(!ret) {
            LOG_ERROR("{} - ES插入User数据失败", request->request_id());
            return errorResp("ES插入User数据失败");
        }
        // 7.组织响应，进行成功与否的响应即可。
        response->set_success(true);
    }

    void UserLogin(::google::protobuf::RpcController* controller,
                         const ::zhiang::UserLoginReq* request,
                         ::zhiang::UserLoginRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        // 1.从请求中取出昵称和密码 
        std::string nickname = request->nickname();
        std::string password = request->password();
        // 2.通过昵称获取用户信息，进行密码是否一致的判断 
        std::shared_ptr<User> user = _mysql_user->select_by_nickname(nickname);
        if(!user) {
            LOG_INFO("{} 用户不存在", nickname);
            return errorResp("用户不存在");
        }
        if(user->password() != password) {
            LOG_ERROR("密码错误!");
            return errorResp("密码错误");
        }
        // 3.根据redis中的登录标记信息是否存在判断用户是否已经登录。 
        bool ret = _redis_status->exist(user->user_id());
        if(ret) {
            LOG_INFO("{} - 该账号已在其他地方登录", nickname);
            return errorResp("该账号已在其他地方登录");
        }
        // 4.构造会话ID，生成会话键值对，向redis中添加会话信息以及登录标记信息 
        std::string ssid = generate_uid();
        _redis_session->append(ssid, user->user_id());
        _redis_status->append(user->user_id());
        // 5.组织响应，返回生成的会话ID 
        response->set_success(true);
        response->set_login_session_id(ssid);
    }

    void GetPhoneVerifyCode(::google::protobuf::RpcController* controller,
                         const ::zhiang::PhoneVerifyCodeReq* request,
                         ::zhiang::PhoneVerifyCodeRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        // 从请求中取出手机号码 
        std::string phone = request->phone_number();
        // 验证手机号码格式是否正确
        bool ret = check_phone(phone);
        if(!ret) {
            LOG_ERROR("电话号码 {} 不合法", phone);
            return errorResp("电话号码不合法");
        }
        // 生成4位随机验证码 
        std::string code = generate_code();
        // 基于短信平台SDK发送验证码 
        ret = _dms_client->send(phone, code);
        if(!ret) {
            LOG_ERROR("验证码发送失败");
            return errorResp("验证码发送失败");
        }
        // 构造验证码ID，添加到redis验证码映射键值索引中 
        std::string code_id = generate_uid();
        _redis_codes->append(code_id, code);
        // 组织响应，返回生成的验证码ID
        response->set_success(true);
        response->set_verify_code_id(code_id);
    }

    void PhoneRegister(::google::protobuf::RpcController* controller,
                         const ::zhiang::PhoneRegisterReq* request,
                         ::zhiang::PhoneRegisterRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        // 从请求中取出手机号码和验证码 
        std::string phone = request->phone_number();
        std::string code = request->verify_code();
        std::string cid = request->verify_code_id();
        // 检查注册手机号码是否合法 
        bool ret = check_phone(phone);
        if(!ret) {
            LOG_ERROR("电话号码 {} 不合法", phone);
            return errorResp("电话号码不合法");
        }
        // 从redis数据库中进行验证码ID-验证码一致性匹配 
        sw::redis::OptionalString redis_code = _redis_codes->code(cid);
        if(!redis_code.has_value() || *redis_code != code) {
            LOG_WARN("验证码错误");
            return errorResp("验证码错误");
        }
        // 通过数据库查询判断手机号是否已经注册过 
        std::shared_ptr<User> user = _mysql_user->select_by_phone(phone);
        if(user) {
            LOG_ERROR("该电话号已被注册");
            return errorResp("该电话号已被注册");
        }
        // 向数据库新增用户信息 
        std::string uid = generate_uid();
        user = std::make_shared<User>(uid, phone);
        ret = _mysql_user->insert(user);
        if(!ret) {
            LOG_ERROR("用户添加mysql数据库失败");
            return errorResp("用户添加mysql数据库失败");
        }
        // 向ES服务器中新增用户信息 
        ret = _es_user->appendData(user->user_id(), user->nickname(), user->description(), user->phone(), user->avatar_id());
        if(!ret) {
            LOG_ERROR("用户添加es数据库失败");
            return errorResp("用户添加es数据库失败");
        }
        // 组织响应，返回注册成功与否
        response->set_success(true);
    }

    void PhoneLogin(::google::protobuf::RpcController* controller,
                         const ::zhiang::PhoneLoginReq* request,
                         ::zhiang::PhoneLoginRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        // 从请求中取出手机号码和验证码ID，以及验证码。 
        std::string phone = request->phone_number();
        std::string code = request->verify_code();
        std::string cid = request->verify_code_id();
        // 检查注册手机号码是否合法 
        bool ret = check_phone(phone);
        if(!ret) {
            LOG_ERROR("{} - 电话号码 {} 不合法", request->request_id(), phone);
            return errorResp("电话号码不合法");
        }
        // 从redis数据库中进行验证码ID-验证码一致性匹配 
        sw::redis::OptionalString redis_code = _redis_codes->code(cid);
        if(!redis_code.has_value() || *redis_code != code) {
            LOG_WARN("{} - 验证码错误: {}", request->request_id(), *redis_code);
            return errorResp("验证码错误");
        }
        // 根据手机号从数据数据进行用户信息查询，判断用用户是否存在 
        std::shared_ptr<User> user = _mysql_user->select_by_phone(phone);
        if(!user) {
            LOG_WARN("{} - 该用户不存在", request->request_id());
            return errorResp("该用户不存在");
        }
        // 根据redis中的登录标记信息是否存在判断用户是否已经登录。
        ret = _redis_status->exist(user->user_id());
        if(ret) {
            LOG_ERROR("{} - 该用户已登录", request->request_id());
            return errorResp("该用户已登录");
        }
        // 构造会话ID，生成会话键值对，向redis中添加会话信息以及登录标记信息 
        std::string ssid = generate_uid();
        _redis_session->append(ssid, user->user_id());
        _redis_status->append(user->user_id());
        // 组织响应，返回生成的会话ID 
        response->set_success(true);
        response->set_login_session_id(ssid);
    }

    void GetUserInfo(::google::protobuf::RpcController* controller,
                         const ::zhiang::GetUserInfoReq* request,
                         ::zhiang::GetUserInfoRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        // 请求中取出用户ID 
        std::string uid = request->user_id();
        // 通过用户ID，从数据库中查询用户信息 
        std::shared_ptr<User> user = _mysql_user->select_by_id(uid);
        // 根据用户信息中的头像ID，从文件服务器获取头像文件数据，组织完整用户信息 
        ServiceChannel::ChannelPtr channel = _serviceManage_channal->choose(_discovery_file_name);
        if (!channel)
        {
            LOG_ERROR("{} - 文件传输模块channel为空", request->request_id());
            return errorResp("文件传输模块channel为空");
        }
        UserInfo* user_info = response->mutable_user_info();
        if(!user->avatar_id().empty()){
            zhiang::FileService_Stub stub(channel.get());
            brpc::Controller cntl;
            zhiang::GetSingleFileReq req;
            zhiang::GetSingleFileRsp resp;
            req.set_request_id(request->request_id());
            req.set_file_id(user->avatar_id());
            stub.GetSingleFile(&cntl, &req, &resp, nullptr);
            if(cntl.Failed() == true || resp.success() == false) {
                LOG_ERROR("{} - 用户获取头像{}失败: {}", response->request_id(), user->avatar_id(), cntl.ErrorText());
                return errorResp("用户获取头像失败");
            }
            user_info->set_avatar(resp.file_data().file_content());
        }
        user_info->set_user_id(uid);
        user_info->set_nickname(user->nickname());
        user_info->set_phone(user->phone());
        user_info->set_description(user->description());
        

        // 组织响应，返回用户信息 
        response->set_success(true);
    }

    void GetMultiUserInfo(::google::protobuf::RpcController* controller,
                         const ::zhiang::GetMultiUserInfoReq* request,
                         ::zhiang::GetMultiUserInfoRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        // 从请求中取出用户ID 
        std::vector<std::string> uids;
        // std::unordered_set<std::string> hash_uids;
        for(int i = 0; i < request->users_id_size(); i++) {
            // if(hash_uids.count(request->users_id(i))) continue;
            // hash_uids.insert(request->users_id(i));
            uids.push_back(request->users_id(i));
            LOG_DEBUG("请求ID: {}", request->users_id(i));
        }
        // 通过用户ID，从数据库中查询用户信息 
        std::vector<User> users = _mysql_user->select_multi_users(uids);
        LOG_DEBUG("获取ID数量: {}", users.size());
        if(users.size() != uids.size()) {
            LOG_ERROR("{} - 数据库中有部分成员没有", request->request_id());
            return errorResp("数据库中有部分成员没有");
        }
        // 根据用户信息中的头像ID，从文件服务器获取头像文件数据，组织完整用户信息 
        ServiceChannel::ChannelPtr channel = _serviceManage_channal->choose(_discovery_file_name);
        if (!channel)
        {
            LOG_ERROR("{} - 文件下载模块channel为空", request->request_id());
            return errorResp("文件下载模块channel为空");
        }
        zhiang::FileService_Stub stub(channel.get());
        brpc::Controller cntl;
        zhiang::GetMultiFileReq req;
        zhiang::GetMultiFileRsp resp;
        req.set_request_id(request->request_id());
        for(auto& user : users) {
            if(!user.avatar_id().empty()) 
                req.add_file_id_list(user.avatar_id());
        }
        // 发起EchoRpc调用
        stub.GetMultiFile(&cntl, &req, &resp, nullptr);
        if(cntl.Failed() == true || resp.success() == false) {
            LOG_ERROR("{} - 用户获取头像失败: {}", request->request_id(), cntl.ErrorText());
            return errorResp("用户获取头像失败");
        }
        // 组织响应，返回用户信息 
        for(auto& user : users) {
            auto user_map = response->mutable_users_info();
            auto file_map = resp.mutable_file_data();
            UserInfo user_info;
            user_info.set_user_id(user.user_id());
            user_info.set_nickname(user.nickname());
            user_info.set_phone(user.phone());
            user_info.set_description(user.description());
            user_info.set_avatar((*file_map)[user.avatar_id()].file_content());
            (*user_map)[user.user_id()] = user_info;
        } 
        response->set_success(true);
    }

    void SetUserAvatar(::google::protobuf::RpcController* controller,
                         const ::zhiang::SetUserAvatarReq* request,
                         ::zhiang::SetUserAvatarRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        // 请求中取出用户ID与头像数据 
        // 从数据库通过用户ID进行用户信息查询，判断用户是否存在 
        std::string uid = request->user_id();
        std::shared_ptr<User> user = _mysql_user->select_by_id(uid);
        if(!user) {
            LOG_ERROR("{} - 数据库中没有该成员", uid);
            return errorResp("数据库中没有该成员");
        }

        auto avatar = request->avatar();
        // 上传头像文件到文件子服务
        ServiceChannel::ChannelPtr channel = _serviceManage_channal->choose(_discovery_file_name);
        if (!channel)
        {
            LOG_ERROR("{} - 文件下载模块channel为空", request->request_id());
            return errorResp("文件下载模块channel为空");
        }
        zhiang::FileService_Stub stub(channel.get());

        brpc::Controller cntl1;
        brpc::Controller cntl2;
        std::string old_avatar_id = user->avatar_id();
        if(old_avatar_id.empty() == false) {
            zhiang::DelSingleFileReq dreq;
            dreq.set_request_id(request->request_id());
            dreq.set_file_id(old_avatar_id);
            zhiang::DelSingleFileRsp dresp;
            stub.DelSingleFile(&cntl1, &dreq, &dresp, nullptr);
            if(cntl1.Failed() == true || dresp.success() == false) {
                LOG_ERROR("{} - 删除头像失败", request->request_id());
            }
        }
        
        zhiang::PutSingleFileReq req;
        req.set_request_id(request->request_id());
        zhiang::FileUploadData* data = req.mutable_file_data();
        data->set_file_content(avatar);
        data->set_file_name(uid);
        data->set_file_size(avatar.size());
        zhiang::PutSingleFileRsp resp;
        // 4. 发起EchoRpc调用
        stub.PutSingleFile(&cntl2, &req, &resp, nullptr);
        if(cntl2.Failed() == true || resp.success() == false) {
            LOG_ERROR("{} - 用户上传头像失败", request->request_id());
            return errorResp("用户上传头像失败");
        }

        // 更新MySQL服务器中用户信息 
        user->avatar_id(resp.file_info().file_id());
        bool ret = _mysql_user->update(user);
        if(!ret) {
            LOG_ERROR("{} - 数据库更新头像失败", request->request_id());
            return errorResp("数据库更新头像失败");
        }
        // 更新ES服务器中用户信息 
        ret = _es_user->appendData(user->user_id(), user->nickname(), user->description(), user->phone(), user->avatar_id());
        if(!ret) {
            LOG_ERROR("{} - 用户更新es数据库失败", request->request_id());
            return errorResp("用户更新es数据库失败");
        }
        // 组织响应，返回更新成功与否
        response->set_success(true);
    }

    void SetUserNickname(::google::protobuf::RpcController* controller,
                         const ::zhiang::SetUserNicknameReq* request,
                         ::zhiang::SetUserNicknameRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        std::string uid = request->user_id();
        std::shared_ptr<User> user = _mysql_user->select_by_id(uid);
        if(!user) {
            LOG_ERROR("{} - 数据库中没有该成员", request->request_id());
            return errorResp("数据库中没有该成员");
        }
        auto new_nickname = request->nickname();
        user->nickname(new_nickname);
        bool ret = _mysql_user->update(user);
        if(!ret) {
            LOG_ERROR("{} - 数据库更新昵称失败", request->request_id());
            return errorResp("数据库更新昵称失败");
        }
        // 更新ES服务器中用户信息 
        ret = _es_user->appendData(user->user_id(), user->nickname(), user->description(), user->phone(), user->avatar_id());
        if(!ret) {
            LOG_ERROR("{} - 用户更新es数据库失败", request->request_id());
            return errorResp("用户更新es数据库失败");
        }
        
        response->set_success(true);
    }

    void SetUserDescription(::google::protobuf::RpcController* controller,
                         const ::zhiang::SetUserDescriptionReq* request,
                         ::zhiang::SetUserDescriptionRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        std::string uid = request->user_id();
        std::shared_ptr<User> user = _mysql_user->select_by_id(uid);
        if(!user) {
            LOG_ERROR("{} - 数据库中没有该成员", request->request_id());
            return errorResp("数据库中没有该成员");
        }
        auto new_description = request->description();
        user->description(new_description);
        bool ret = _mysql_user->update(user);
        if(!ret) {
            LOG_ERROR("{} - 数据库更新签名失败", request->request_id());
            return errorResp("数据库更新签名失败");
        }
        // 更新ES服务器中用户信息 
        ret = _es_user->appendData(user->user_id(), user->nickname(), user->description(), user->phone(), user->avatar_id());
        if(!ret) {
            LOG_ERROR("{} - 用户更新es数据库失败", request->request_id());
            return errorResp("用户更新es数据库失败");
        }
        
        response->set_success(true);
    }

    void SetUserPhoneNumber(::google::protobuf::RpcController* controller,
                         const ::zhiang::SetUserPhoneNumberReq* request,
                         ::zhiang::SetUserPhoneNumberRsp* response,
                         ::google::protobuf::Closure* done)  {
        brpc::ClosureGuard done_guard(done);
        response->set_request_id(request->request_id());
        auto errorResp = [this, response](const std::string& errmsg)->void {
            response->set_success(false);
            response->set_errmsg(errmsg);
        };
        std::string uid = request->user_id();
        std::shared_ptr<User> user = _mysql_user->select_by_id(uid);
        if(!user) {
            LOG_ERROR("{} - 数据库中没有该成员", request->request_id());
            return errorResp("数据库中没有该成员");
        }
        std::string code = request->phone_verify_code();
        std::string cid = request->phone_verify_code_id();

        sw::redis::OptionalString redis_code = _redis_codes->code(cid);
        if(!redis_code.has_value() || *redis_code != code) {
            LOG_WARN("{} - 验证码错误", request->request_id());
            return errorResp("验证码错误");
        }

        auto new_phone = request->phone_number();
        user->phone(new_phone);
        bool ret = _mysql_user->update(user);
        if(!ret) {
            LOG_ERROR("{} - 数据库更新签名失败", request->request_id());
            return errorResp("数据库更新签名失败");
        }
        // 更新ES服务器中用户信息 
        ret = _es_user->appendData(user->user_id(), user->nickname(), user->description(), user->phone(), user->avatar_id());
        if(!ret) {
            LOG_ERROR("{} - 用户更新es数据库失败", request->request_id());
            return errorResp("用户更新es数据库失败");
        }
        
        response->set_success(true);
    }

private:
    ESUser::ptr _es_user;
    UserTable::ptr _mysql_user;
    Session::ptr _redis_session;
    Status::ptr _redis_status;
    Codes::ptr _redis_codes;
    ServiceManage::ptr _serviceManage_channal;
    std::string _discovery_file_name;
    DMSClient::ptr _dms_client;
};

class UserServer {
public:
    using ptr = std::shared_ptr<UserServer>;
    UserServer(const Registry::ptr& registry_client,
        const std::shared_ptr<brpc::Server> &rpc_server,
        const std::shared_ptr<elasticlient::Client>& es_client,
        const std::shared_ptr<odb::core::database>& mysql_client,
        const std::shared_ptr<sw::redis::Redis>& redis_client,
        const Discovery::ptr& discovery_client, 
        const DMSClient::ptr& dms_client) 
        : _registry_client(registry_client)
        , _rpc_server(rpc_server)
        , _discovery_client(discovery_client)
        , _es_client(es_client)
        , _mysql_client(mysql_client)
        , _redis_client(redis_client)
        , _dms_client(dms_client)
        {}
    ~UserServer() {}
    void start() {
        _rpc_server->RunUntilAskedToQuit();
    }
private:
    
    Registry::ptr _registry_client;
    Discovery::ptr _discovery_client;
    std::shared_ptr<brpc::Server> _rpc_server;
    std::shared_ptr<elasticlient::Client> _es_client;
    std::shared_ptr<odb::core::database> _mysql_client;
    std::shared_ptr<sw::redis::Redis> _redis_client;
    DMSClient::ptr _dms_client;
};

class UserBuilder {
public:
    UserBuilder() {}
    ~UserBuilder() {}
    void make_es_client(const std::vector<std::string>& hosts) {
        _es_client = ESClientFactory::create(hosts);
    }
    void make_mysql_client(const std::string& user, const std::string& pswd, 
        std::string& db, const std::string& host, int port, 
        const std::string& cset, int connect_pool_count) {
        _mysql_client = ODBFactory::create(user, pswd, db, host, port, cset, connect_pool_count);
    }
    void make_redis_client(const std::string& host, int port, int db, bool keep_alive) {
        _redis_client = redisClientFactory::create(host, port, db, keep_alive);
    }
    void make_registry_client(const std::string& host, const std::string& server_name, const std::string& access_host) {
        _registry_client = std::make_shared<Registry>(host);
        int ret = _registry_client->registry(server_name, access_host);
        if(!ret) {
            LOG_ERROR("User服务注册失败！");
            exit(-1);
        }
    }
    void make_discovery_client(const std::string& host, const std::string& basedir, const std::string& discovery_file_name) {
        _serviceManage_channal = std::make_shared<ServiceManage>();
        _discovery_file_name = discovery_file_name;
        _serviceManage_channal->declared(discovery_file_name);
        auto _put_cb = std::bind(&ServiceManage::onServiceOnline, _serviceManage_channal.get(), std::placeholders::_1, std::placeholders::_2);
        auto _del_cb = std::bind(&ServiceManage::onServiceOffline, _serviceManage_channal.get(), std::placeholders::_1, std::placeholders::_2);
        _discovery_client = std::make_shared<Discovery>(host, basedir, _put_cb, _del_cb);
    }
    void make_dms_client(const std::string access_key_id, const std::string access_key_secret) {
        _dms_client = std::make_shared<DMSClient>(access_key_id, access_key_secret);
    }
    void make_rpc_server(int rpc_port, int idle_timeout_sec, int num_threads) {
        if(!_es_client) {
            LOG_ERROR("User服务ES-client创建失败");
            exit(-1);
        }
        if(!_mysql_client) {
            LOG_ERROR("User服务MySQL-client创建失败");
            exit(-1);
        }
        if(!_redis_client) {
            LOG_ERROR("User服务Redis-client创建失败");
            exit(-1);
        }
        if(!_dms_client) {
            LOG_ERROR("User服务DMS-client创建失败");
            exit(-1);
        }
        if(!_serviceManage_channal) {
            LOG_ERROR("User服务_serviceManage_channal初始化失败");
            exit(-1);
        }
        if(!_discovery_client) {
            LOG_ERROR("User服务发现失败");
            exit(-1);
        }
        _rpc_server = std::make_shared<brpc::Server>();
        UserServiceImpl* user_service = new UserServiceImpl(_dms_client, _es_client, _mysql_client,
             _redis_client, _discovery_file_name, _serviceManage_channal);
        int ret = _rpc_server->AddService(user_service, brpc::ServiceOwnership::SERVER_OWNS_SERVICE);
        if(ret == -1) {
            LOG_ERROR("User添加服务失败");
            exit(-1);
        }
        brpc::ServerOptions options;
        options.idle_timeout_sec = idle_timeout_sec; 
        options.num_threads = num_threads;
        ret = _rpc_server->Start(rpc_port, &options);
        if(ret == -1) {
            LOG_ERROR("User添加服务失败");
            exit(-1);
        }
    }
    
    UserServer::ptr build() {
        
        if(!_registry_client) {
            LOG_ERROR("User服务注册失败");
            exit(-1);
        }
        if(!_rpc_server) {
            LOG_ERROR("User服务RPC服务器启动失败");
            exit(-1);
        }
        
        return std::make_shared<UserServer>(_registry_client, _rpc_server, _es_client, _mysql_client, 
            _redis_client,  _discovery_client, _dms_client);
    }
private:
    
    Registry::ptr _registry_client;
    std::shared_ptr<brpc::Server> _rpc_server;

    std::string _discovery_file_name;
    ServiceManage::ptr _serviceManage_channal;
    Discovery::ptr _discovery_client;

    std::shared_ptr<elasticlient::Client> _es_client;
    std::shared_ptr<odb::core::database> _mysql_client;
    std::shared_ptr<sw::redis::Redis> _redis_client;

    DMSClient::ptr _dms_client;
};

}
